package com.chivan.encoder;

import android.Manifest;
import android.content.Intent;
import android.content.pm.PackageManager;
import android.os.Build;
import android.os.Bundle;
import android.util.Log;
import android.view.View;
import android.widget.TextView;

import androidx.annotation.NonNull;
import androidx.appcompat.app.AppCompatActivity;
import androidx.core.app.ActivityCompat;
import androidx.core.content.ContextCompat;

import java.io.File;
import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.io.OutputStream;
import java.util.ArrayList;
import java.util.List;


public class MainActivity extends AppCompatActivity {

    private static final String TAG = "MainActivity";
    private String[] permissions = new String[]{
            Manifest.permission.READ_EXTERNAL_STORAGE,
            Manifest.permission.WRITE_EXTERNAL_STORAGE,
            Manifest.permission.RECORD_AUDIO
    };
    private List<String> mPermissionList = new ArrayList<>();
    private static final int MY_PERMISSIONS_REQUEST = 1001;

    //
//    //采样率，现在能够保证在所有设备上使用的采样率是44100Hz, 但是其他的采样率（22050, 16000, 11025）在一些设备上也可以使用。
//    public static final int SAMPLE_RATE_INHZ = 16000;
//    //声道数。CHANNEL_IN_MONO and CHANNEL_IN_STEREO. 其中CHANNEL_IN_MONO是可以保证在所有设备能够使用的。
//    public static final int CHANNEL_CONFIG = AudioFormat.CHANNEL_OUT_MONO;
//    //返回的音频数据的格式。 ENCODING_PCM_8BIT, ENCODING_PCM_16BIT, and ENCODING_PCM_FLOAT.
//    public static final int AUDIO_FORMAT = AudioFormat.ENCODING_PCM_16BIT;
//
//    public static final int bitRate = 24;
//
//
//    // Used to load the 'native-lib' library on application startup.

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);

        // Example of a call to a native method
        TextView tv_record = findViewById(R.id.sample_text);
        TextView tv_encode = findViewById(R.id.encode);

        checkPermissions();

        tv_record.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                startActivity(new Intent(MainActivity.this, RecordActivity.class));
            }
        });

        tv_encode.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                String pcmPath, mp3Path;
//                pcmPath = "/storage/emulated/0/reverseme.pcm";//pcm文件路径，文件要存在！
//                pcmPath = "/storage/emulated/0/test_pcm.pcm";//pcm文件路径，文件要存在！
//                pcmPath = "/storage/emulated/0/original.pcm";//pcm文件路径，文件要存在！
//                pcmPath = "/storage/emulated/0/test_pcm2.pcm";//pcm文件路径，文件要存在！
                pcmPath = "/storage/emulated/0/qt_record_file-3.pcm";//pcm文件路径，文件要存在！
                mp3Path = "/storage/emulated/0/newmp3.mp3";//转换后mp3文件的保存路径
//                mp3Path = "/storage/emulated/0/qt_record_file-1.mp3";//转换后mp3文件的保存路径
                Mp3Encoder encoder = new Mp3Encoder();
                int result = encoder.init(1, 28, 16000, 5);
                byte[] buffer = new byte[6400];
                try {
                    File file = new File(pcmPath);
                    FileInputStream fis = new FileInputStream(file);
                    File mp3File = new File(mp3Path);
                    OutputStream os = new FileOutputStream(mp3File);
                    Log.i(TAG, "onCreate: encoder-start");
                    int readSize;
                    while ((readSize = fis.read(buffer, 0, 6400)) > 0) {
//                        Log.i(TAG, bytesToHexString(buffer));
//                        Log.i(TAG, "read size:" + readSize);
                        byte[] encodeData = encoder.encode(buffer, readSize);
//                        Log.i(TAG, bytesToHexString(encodeData));
//                        Log.i(TAG, "read size:" + encodeData[1]);
                        os.write(encodeData);
                    }
                    Log.i(TAG, "onCreate:encode finished");
                    encoder.destroy();
                    encoder.destroy();
                    os.close();
                } catch (Exception e) {

                }
            }
        });

    }

    public static String bytesToHexString(byte[] bytes) {
        StringBuilder buf = new StringBuilder(bytes.length * 2);
        for (byte b : bytes) { // 使用String的format方法进行转换
            buf.append(String.format("%02x", new Integer(b & 0xff)));
        }

        return buf.toString().toUpperCase();
    }

    private void checkPermissions() {
        // Marshmallow开始才用申请运行时权限
        if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.M) {
            for (int i = 0; i < permissions.length; i++) {
                if (ContextCompat.checkSelfPermission(this, permissions[i]) !=
                        PackageManager.PERMISSION_GRANTED) {
                    mPermissionList.add(permissions[i]);
                }
            }
            if (!mPermissionList.isEmpty()) {
                String[] permissions = mPermissionList.toArray(new String[mPermissionList.size()]);
                ActivityCompat.requestPermissions(this, permissions, MY_PERMISSIONS_REQUEST);
            }
        }
    }

    @Override
    public void onRequestPermissionsResult(int requestCode, @NonNull String[] permissions, @NonNull int[] grantResults) {
        if (requestCode == MY_PERMISSIONS_REQUEST) {
            for (int i = 0; i < grantResults.length; i++) {
                if (grantResults[i] != PackageManager.PERMISSION_GRANTED) {
                    Log.i(TAG, permissions[i] + " 权限被用户禁止！");
                }
            }
            // 运行时权限的申请不是本demo的重点，所以不再做更多的处理，请同意权限申请。
        }
    }
}
